<template>
  <div id="appEditPage">
    <div class="page-header">
      <h1>编辑应用信息</h1>
    </div>

    <div class="edit-container">
      <a-card title="基本信息" :loading="loading">
        <a-form
          :model="formData"
          :rules="rules"
          layout="vertical"
          @finish="handleSubmit"
          ref="formRef"
        >
          <a-form-item label="应用名称" name="appName">
            <a-input
              v-model:value="formData.appName"
              placeholder="请输入应用名称"
              :maxlength="50"
              show-count
            />
          </a-form-item>

          <a-form-item
            v-if="isAdmin"
            label="应用封面"
            name="cover"
            extra="支持图片链接，建议尺寸：400x300"
          >
            <a-input v-model:value="formData.cover" placeholder="请输入封面图片链接" />
            <div v-if="formData.cover" class="cover-preview">
              <a-image
                :src="formData.cover"
                :width="200"
                :height="150"
                fallback=""
              />
            </div>
          </a-form-item>

          <a-form-item v-if="isAdmin" label="优先级" name="priority" extra="设置为99表示精选应用">
            <a-input-number
              v-model:value="formData.priority"
              :min="0"
              :max="99"
              style="width: 200px"
            />
          </a-form-item>

          <a-form-item label="初始提示词" name="initPrompt">
            <a-textarea
              v-model:value="formData.initPrompt"
              placeholder="请输入初始提示词"
              :rows="4"
              :maxlength="1000"
              show-count
              disabled
            />
            <div class="form-tip">初始提示词不可修改</div>
          </a-form-item>

          <a-form-item label="生成类型" name="codeGenType">
            <a-input
              :value="formatCodeGenType(formData.codeGenType)"
              placeholder="生成类型"
              disabled
            />
            <div class="form-tip">生成类型不可修改</div>
          </a-form-item>

          <a-form-item v-if="formData.deployKey" label="部署密钥" name="deployKey">
            <a-input v-model:value="formData.deployKey" placeholder="部署密钥" disabled />
            <div class="form-tip">部署密钥不可修改</div>
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="submitting">
                保存修改
              </a-button>
              <a-button @click="resetForm">重置</a-button>
              <a-button type="link" @click="goToChat">进入对话</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 应用信息展示 -->
      <a-card title="应用信息" style="margin-top: 24px">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="应用ID">
            {{ appInfo?.id }}
          </a-descriptions-item>
          <a-descriptions-item label="创建者">
            <UserInfo :user="appInfo?.user" size="small" />
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatTime(appInfo?.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatTime(appInfo?.updateTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="部署时间">
            {{ appInfo?.deployedTime ? formatTime(appInfo.deployedTime) : '未部署' }}
          </a-descriptions-item>
          <a-descriptions-item label="访问链接">
            <a-button v-if="appInfo?.deployKey" type="link" @click="openPreview" size="small">
              查看预览
            </a-button>
            <span v-else>未部署</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { getAppVoById, updateApp, updateAppByAdmin } from '@/api/appController'
import { formatCodeGenType } from '@/utils/codeGenTypes'
import { formatTime } from '@/utils/time'
import UserInfo from '@/components/UserInfo.vue'
import { getStaticPreviewUrl } from '@/config/env'
import type { FormInstance } from 'ant-design-vue'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

// 应用信息
const appInfo = ref<API.AppVO>()
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  appName: '',
  cover: '',
  priority: 0,
  initPrompt: '',
  codeGenType: '',
  deployKey: '',
})

// 是否为管理员
const isAdmin = computed(() => {
  return loginUserStore.loginUser.userRole === 'admin'
})

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 1, max: 50, message: '应用名称长度在1-50个字符', trigger: 'blur' },
  ],
  cover: [{ type: 'url', message: '请输入有效的URL', trigger: 'blur' }],
  priority: [{ type: 'number', min: 0, max: 99, message: '优先级范围0-99', trigger: 'blur' }],
}

// 获取应用信息
const fetchAppInfo = async () => {
  const id = route.params.id as string
  if (!id) {
    message.error('应用ID不存在')
    router.push('/')
    return
  }

  loading.value = true
  try {
    const res = await getAppVoById({ id: id as unknown as number })
    if (res.data.code === 0 && res.data.data) {
      appInfo.value = res.data.data

      // 检查权限
      if (!isAdmin.value && appInfo.value.userId !== loginUserStore.loginUser.id) {
        message.error('您没有权限编辑此应用')
        router.push('/')
        return
      }

      // 填充表单数据
      formData.appName = appInfo.value.appName || ''
      formData.cover = appInfo.value.cover || ''
      formData.priority = appInfo.value.priority || 0
      formData.initPrompt = appInfo.value.initPrompt || ''
      formData.codeGenType = appInfo.value.codeGenType || ''
      formData.deployKey = appInfo.value.deployKey || ''
    } else {
      message.error('获取应用信息失败')
      router.push('/')
    }
  } catch (error) {
    console.error('获取应用信息失败：', error)
    message.error('获取应用信息失败')
    router.push('/')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!appInfo.value?.id) return

  submitting.value = true
  try {
    let res
    if (isAdmin.value) {
      // 管理员可以修改更多字段
      res = await updateAppByAdmin({
        id: appInfo.value.id,
        appName: formData.appName,
        cover: formData.cover,
        priority: formData.priority,
      })
    } else {
      // 普通用户只能修改应用名称
      res = await updateApp({
        id: appInfo.value.id,
        appName: formData.appName,
      })
    }

    if (res.data.code === 0) {
      message.success('修改成功')
      // 重新获取应用信息
      await fetchAppInfo()
    } else {
      message.error('修改失败：' + res.data.message)
    }
  } catch (error) {
    console.error('修改失败：', error)
    message.error('修改失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (appInfo.value) {
    formData.appName = appInfo.value.appName || ''
    formData.cover = appInfo.value.cover || ''
    formData.priority = appInfo.value.priority || 0
  }
  formRef.value?.clearValidate()
}

// 进入对话页面
const goToChat = () => {
  if (appInfo.value?.id) {
    router.push(`/app/chat/${appInfo.value.id}`)
  }
}

// 打开预览
const openPreview = () => {
  if (appInfo.value?.codeGenType && appInfo.value?.id) {
    const url = getStaticPreviewUrl(appInfo.value.codeGenType, String(appInfo.value.id))
    window.open(url, '_blank')
  }
}

// 页面加载时获取应用信息
onMounted(() => {
  fetchAppInfo()
})
</script>

<style scoped>
#appEditPage {
  min-height: 100vh;
  padding: 32px 24px 48px;
  max-width: 1100px;
  margin: 0 auto;
  background:
    radial-gradient(circle at 12% 18%, rgba(59, 130, 246, 0.25) 0%, transparent 55%),
    radial-gradient(circle at 88% 12%, rgba(236, 72, 153, 0.22) 0%, transparent 58%),
    linear-gradient(180deg, rgba(10, 12, 24, 0.96) 0%, rgba(12, 17, 33, 0.92) 35%, rgba(5, 9, 20, 0.98) 100%);
  position: relative;
  overflow: hidden;
}

#appEditPage::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(94, 234, 212, 0.08) 1px, transparent 1px),
    linear-gradient(90deg, rgba(94, 234, 212, 0.08) 1px, transparent 1px);
  background-size: 120px 120px;
  opacity: 0.28;
  mix-blend-mode: screen;
  pointer-events: none;
}

#appEditPage > * {
  position: relative;
  z-index: 2;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: rgba(248, 250, 252, 0.95);
  background: linear-gradient(135deg, #38bdf8 0%, #8b5cf6 45%, #22d3ee 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.edit-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 28px;
  border-radius: 18px;
  background: rgba(13, 18, 32, 0.86);
  backdrop-filter: blur(22px);
  border: 1px solid rgba(148, 163, 184, 0.22);
  box-shadow:
    0 20px 60px rgba(2, 6, 23, 0.65),
    0 0 0 1px rgba(59, 130, 246, 0.08);
}

.cover-preview {
  margin-top: 12px;
  padding: 12px;
  border: 1px solid rgba(148, 163, 184, 0.32);
  border-radius: 10px;
  background: rgba(23, 32, 55, 0.68);
  box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.08);
}

.form-tip {
  font-size: 12px;
  color: rgba(226, 232, 240, 0.65);
  margin-top: 4px;
}

:deep(.ant-card) {
  background: rgba(18, 24, 40, 0.88) !important;
  border-radius: 16px !important;
  border: 1px solid rgba(148, 163, 184, 0.18) !important;
  box-shadow:
    0 15px 45px rgba(2, 6, 23, 0.55),
    0 0 0 1px rgba(59, 130, 246, 0.08);
}

:deep(.ant-card-head) {
  background: linear-gradient(180deg, rgba(24, 33, 55, 0.88) 0%, rgba(18, 24, 40, 0.9) 100%) !important;
  border-bottom: 1px solid rgba(148, 163, 184, 0.16) !important;
}

:deep(.ant-card-head-title) {
  color: rgba(241, 245, 249, 0.96) !important;
  font-weight: 600 !important;
}

:deep(.ant-card-body) {
  background: transparent !important;
  color: rgba(226, 232, 240, 0.9) !important;
  padding: 24px 24px 28px !important;
}

:deep(.ant-form) {
  color: rgba(226, 232, 240, 0.9);
}

:deep(.ant-form-item-label > label) {
  color: rgba(241, 245, 249, 0.9) !important;
  font-weight: 500;
}

:deep(.ant-form-item-explain-error) {
  color: #fca5a5 !important;
}

:deep(.ant-input),
:deep(.ant-input-affix-wrapper),
:deep(.ant-input-number),
:deep(.ant-input-number-input),
:deep(.ant-input-number-handler-wrap) {
  background: rgba(23, 32, 55, 0.72) !important;
  border-color: rgba(94, 234, 212, 0.18) !important;
  color: rgba(226, 232, 240, 0.92) !important;
}

:deep(.ant-input),
:deep(.ant-input-number-input) {
  transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}

:deep(.ant-input:hover),
:deep(.ant-input-number:hover),
:deep(.ant-input-number-input:hover) {
  border-color: rgba(59, 130, 246, 0.45) !important;
}

:deep(.ant-input:focus),
:deep(.ant-input-number:focus-within),
:deep(.ant-input-affix-wrapper-focused) {
  border-color: rgba(59, 130, 246, 0.7) !important;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.18) !important;
  background: rgba(23, 32, 55, 0.84) !important;
}

:deep(.ant-input::placeholder),
:deep(.ant-input-number-input::placeholder) {
  color: rgba(148, 163, 184, 0.55) !important;
}

:deep(.ant-input[disabled]),
:deep(.ant-input-number-disabled) {
  background: rgba(17, 24, 39, 0.6) !important;
  border-color: rgba(148, 163, 184, 0.25) !important;
  color: rgba(148, 163, 184, 0.7) !important;
}

:deep(.ant-input-number-handler-wrap) {
  background: transparent !important;
  border-left: 1px solid rgba(59, 130, 246, 0.18) !important;
}

:deep(.ant-input-number-handler) {
  background: transparent !important;
  color: rgba(226, 232, 240, 0.75) !important;
}

:deep(.ant-input-number-handler:hover) {
  color: rgba(59, 130, 246, 0.9) !important;
}

:deep(.ant-descriptions) {
  background: rgba(10, 14, 26, 0.45);
  border: 1px solid rgba(148, 163, 184, 0.16);
  border-radius: 14px;
  padding: 16px;
}

:deep(.ant-descriptions-bordered .ant-descriptions-item-label),
:deep(.ant-descriptions-bordered .ant-descriptions-item-content) {
  border-color: rgba(148, 163, 184, 0.18) !important;
}

:deep(.ant-descriptions-item-label) {
  background: rgba(24, 33, 55, 0.65);
  font-weight: 500;
  color: rgba(241, 245, 249, 0.9);
}

:deep(.ant-descriptions-item-content) {
  color: rgba(203, 213, 225, 0.85);
}

:deep(.ant-btn) {
  height: 38px;
  padding: 0 18px;
  border-radius: 12px !important;
  font-weight: 500;
  background: rgba(30, 41, 59, 0.92);
  border: 1px solid rgba(148, 163, 184, 0.25);
  color: rgba(226, 232, 240, 0.9);
  transition: all 0.2s ease;
  box-shadow: 0 8px 22px rgba(2, 6, 23, 0.45);
}

:deep(.ant-btn:hover) {
  border-color: rgba(96, 165, 250, 0.7);
  color: #93c5fd;
  transform: translateY(-1px);
  box-shadow: 0 14px 26px rgba(30, 64, 175, 0.35);
}

:deep(.ant-btn:focus-visible) {
  outline: none;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.28);
}

:deep(.ant-btn-primary) {
  color: #0f172a !important;
  background: linear-gradient(135deg, #38bdf8 0%, #60a5fa 52%, #8b5cf6 100%) !important;
  border: none !important;
  box-shadow:
    0 16px 32px rgba(59, 130, 246, 0.45),
    0 0 24px rgba(59, 130, 246, 0.4);
}

:deep(.ant-btn-primary:hover) {
  filter: brightness(1.07);
  transform: translateY(-2px);
}

:deep(.ant-btn[disabled]) {
  background: rgba(15, 23, 42, 0.6) !important;
  border-color: rgba(148, 163, 184, 0.18) !important;
  color: rgba(148, 163, 184, 0.5) !important;
  box-shadow: none;
  transform: none;
}

:deep(.ant-btn-link) {
  background: transparent !important;
  border: none !important;
  color: rgba(129, 230, 217, 0.92) !important;
  box-shadow: none;
  padding-inline: 0;
}

:deep(.ant-btn-link:hover) {
  color: rgba(244, 114, 182, 0.9) !important;
  text-shadow: 0 0 12px rgba(244, 114, 182, 0.35);
}
</style>
